import { GridController, MDCtrlLoadParams } from '@ibiz-template/runtime';

export class AggGridController extends GridController {
  /**
   * 部件加载数据行为
   *
   * @date 2022-08-19 14:08:50
   */
  async load(args: MDCtrlLoadParams = {}): Promise<IData[]> {
    if (this.state.isSimple) {
      return [];
    }
    await this.startLoading();
    try {
      //  *初始加载需要重置分页
      const isInitialLoad = args.isInitialLoad === true;
      const isLoadMore = args.isLoadMore === true;
      if (isInitialLoad) {
        this.state.curPage = 1;
      } else if (isLoadMore) {
        this.state.curPage += 1;
      }

      // *查询参数处理
      const { context } = this.handlerAbilityParams(args);
      const params = await this.getFetchParams(args?.viewParam);
      const res: IData = {};
      // 这里查询的时候查询本地数据
      const dataItems = [
        {
          entityId: 'zc_cx_zrr',
          fetch: 'fetchdefault',
        },
        {
          entityId: 'zc_cx_qyjg',
          fetch: 'fetchdefault',
        },
      ];
      const app = ibiz.hub.getApp(context.srfappid);
      const items = dataItems.map((item: IData) => {
        return app.deService.exec(item.entityId, item.fetch, context, params);
      });
      await Promise.all(items).then(async (response: IData) => {
        if (response) {
          response.forEach((_res: IData, index: number) => {
            const data = _res.data;
            if (index === 0) {
              res.data = data;
              res.total = data.length;
            } else {
              res.data.push(...data);
              res.total += data.length;
            }
          });
          res.data.forEach((item: IData) => {
            const trmpItem = item;
            const index = item.srfdeid.indexOf('zc_cx_qyjg');
            trmpItem.id = item[item.srfkeyfield];
            if (index > -1) {
              trmpItem.name = item.dwmc;
            } else {
              trmpItem.name = item[item.srfmajorfield];
            }
          });
        }
      });
      // 更新分页数据总条数
      if (typeof res.total === 'number') {
        this.state.total = res.total;
      }

      if (isLoadMore) {
        this.state.items.push(...res.data);
      } else {
        this.state.items = res.data;
      }

      await this.afterLoad(args, res.data);

      this.state.isLoaded = true;
      await this._evt.emit('onLoadSuccess', {
        isInitialLoad,
      });
    } catch (error) {
      await this._evt.emit('onLoadError', undefined);
      this.actionNotification('FETCHERROR', {
        error: error as Error,
      });
      throw error;
    } finally {
      await this.endLoading();
    }

    this.actionNotification('FETCHSUCCESS');
    return this.state.items;
  }
}
